package cn.dankal.flyaudio.wxapi;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jyj.recruitment.wxapi.WxConstants;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


import java.util.HashMap;

import api.UserServiceFactory;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.DankalApplication;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.UserInfoBean;
import cn.dankal.basiclib.pojo.UserResponseBody;
import cn.dankal.basiclib.pojo.WXIsBindBean;
import cn.dankal.basiclib.protocol.LoginProtocol;
import cn.dankal.basiclib.rx.AbstractDialogSubscriber;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.business.Constants;

import static cn.dankal.business.Constants.Chinese;
import static cn.dankal.business.Constants.LANGUAGE;
import static cn.dankal.business.Constants.TYPE;

/**
 * description: 微信
 *
 * @author vane
 * @since 2018/3/14
 */

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    private IWXAPI iwxapi;

    public static final String WX_APP_ID = WxConstants.WX_APP_ID;
    private static final String TAG = "WXEntryActivity";


    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iwxapi = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);
        iwxapi.registerApp(WX_APP_ID);
        iwxapi.handleIntent(getIntent(), this);
    }

    @Override
    protected void initComponents() {

        iwxapi = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);
        iwxapi.registerApp(WX_APP_ID);
        iwxapi.handleIntent(getIntent(), this);
    }


    @Override
    public void onReq(BaseReq baseReq) {
        Log.e(TAG, "onReq: ");
    }

    @SuppressLint("CheckResult")
    @Override
    public void onResp(BaseResp resp) {

        switch (resp.errCode)
        {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case ConstantsAPI.COMMAND_SENDAUTH:

                        //登录成功的回调
                        SendAuth.Resp resp1 = (SendAuth.Resp) resp;
                        String code = resp1.code;

                        UserServiceFactory.isBind(code).subscribe(new AbstractDialogSubscriber<WXIsBindBean>(this) {
                            @Override
                            public void onNext(WXIsBindBean wxIsBindBean) {

                                UserResponseBody userResponseBody = new UserResponseBody();
                                UserResponseBody.TokenBean tokenBean=new UserResponseBody.TokenBean();
                                tokenBean.token=wxIsBindBean.getAccessToken();
                                userResponseBody.setToken(tokenBean);
                                DKUserManager.saveUserInfo(userResponseBody);
                                DankalApplication.openId=wxIsBindBean.getOpenId();

                                if (wxIsBindBean.getIsBinding()==1) {
                                    login();
                                } else {
                                    showToast("请绑定手机号");

                                    ARouter.getInstance().build(LoginProtocol.UNBIND_BIND_PHONE)
                                            .withString(TYPE, Constants.TYPE_REGISTER)
                                            .navigation();
                                    WXEntryActivity.this.finish();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                WXEntryActivity.this.finish();
                            }
                        });
                        break;
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                        //分享成功的回调
                        //showToast("微信分享成功");
                        WXEntryActivity.this.finish();
                        break;
                    default:
                        break;
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                switch (resp.getType()) {
                    case ConstantsAPI.COMMAND_SENDAUTH:
                        //登录取消的回调
                        showToast("微信登录取消");
                        WXEntryActivity.this.finish();
                        break;
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                        Log.i("JavaUnity", "分享取消");
                        //分享取消的回调
                        //showToast("微信分享取消");
                        WXEntryActivity.this.finish();
                        break;
                    default:
                        break;
                }
                break;
            default:
                switch (resp.getType()) {
                    case ConstantsAPI.COMMAND_SENDAUTH:
                        //登录失败的回调
                        showToast("微信授权失败");
                        WXEntryActivity.this.finish();
                        break;
                    case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
                        //分享失败的回调
                        showToast("微信授权失败");
                        WXEntryActivity.this.finish();
                        break;
                    default:
                        break;
                }
                break;
        }

    }
//c6673b61af8fcf73dc35c4 ,c6673b61af8fcf73dc35c4
    private void login() {
        UserServiceFactory.wxLogin(new HashMap<String,String>(2){{
            put("openId",DankalApplication.openId);
            put("accessToken", DKUserManager.getUserToken().token);
            put(LANGUAGE,Chinese);

        }}).subscribe(new AbstractSubscriber<UserInfoBean>(this) {
            @Override
            public void onNext(UserInfoBean userInfoBean) {
                DankalApplication.openId=null;
                UserResponseBody userResponseBody = new UserResponseBody();
                UserResponseBody.TokenBean tokenBean = new UserResponseBody.TokenBean();
                tokenBean.token = userInfoBean.getAccessToken();
                tokenBean.fgToken = userInfoBean.getFgToken();
                userResponseBody.setToken(tokenBean);
                userResponseBody.setUserInfo(userInfoBean);
                DKUserManager.saveUserInfo(userResponseBody);
                DKUserManager.updateUserInfo(userInfoBean);
                Log.d("WXEntryActivity","accessToken:"+userInfoBean.getAccessToken());
                LiveEventBus.get("wx_login",String.class).post("");
                finish();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                finish();
            }
        });
    }


    public void showToast(String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        iwxapi.handleIntent(intent, this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        iwxapi.unregisterApp();
    }




}
